﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.FormService;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TZ.PlugIn.FileSrv
{
    [Description("采购订单撤回或作废合同文件")]
    [Kingdee.BOS.Util.HotUpdate]

    public class PurOrderRecallFile : AbstractBillPlugIn
    {
        public override void BarItemClick(Kingdee.BOS.Core.DynamicForm.PlugIn.Args.BarItemClickEventArgs e)
        {
            base.BarItemClick(e);
            if (e.BarItemKey.EqualsIgnoreCase("tbRecallFile")) //撤回合同文件
            {
                var FContractId = "";
                if (!this.View.Model.GetValue("FContractId").IsNullOrEmpty())
                    FContractId = this.View.Model.GetValue("FContractId").ToString().Trim();
                if (FContractId == "")
                {
                    this.View.ShowMessage("没有创建电子签约单！");
                    return;
                }

                var FisRecallBill = Convert.ToBoolean(this.View.Model.GetValue("FisRecallBill").ToString());//是否已撤回合同文件
                //if (FisRecallBill)
                //{
                //    this.View.ShowMessage("已撤回电子签约，不允许重复撤回！");
                //    return;
                //}

                this.View.ShowMessage("确实要撤回吗？", MessageBoxOptions.YesNo,
                new Action<MessageBoxResult>((MsgResult) =>
                {
                    if (MsgResult == MessageBoxResult.Yes)
                    {
                        var BillNo = this.View.Model.GetValue("FBillNo").ToString();
                        var ErrMsg = "";
                        var isPost = true;
                        Common.GetParams(this.Context);
                        var result = Common.PostRecall(Common.RecallBillUrl, Common.AppToken, Common.AppSecret, FContractId, "金蝶撤回", ref isPost);
                        if (!isPost)
                        {
                            ErrMsg = result.ToString().Trim();
                            this.View.ShowErrMessage(ErrMsg);
                        }
                        else
                        {
                            var JsonResult = result as JObject;
                            if (JsonResult["code"].ToString() != "0")
                            {
                                ErrMsg = "code【" + JsonResult["code"].ToString().Trim() + "】,message【" + JsonResult["message"].ToString().Trim() + "】";
                                var sql = string.Format("update T_PUR_POORDER set FRECMESSAGE = '{1}' where FBILLNO = '{0}'", BillNo, ErrMsg);
                                DBUtils.Execute(this.Context, sql);
                                this.View.ShowErrMessage(ErrMsg);
                            }
                            else
                            {
                                var sql = string.Format("update T_PUR_POORDER set FISRECALLBILL = 1,FRECMESSAGE = '撤回成功' where FBILLNO = '{0}'", BillNo);
                                DBUtils.Execute(this.Context, sql);
                                this.View.ShowMessage("撤回成功！");

                                //撤回时删除已经上传的附件
                                var InterId = this.View.Model.DataObject["Id"].ToString();
                                var FileName = BillNo + ".PDF";//定义文件名：单据编号为文件名
                                sql = string.Format("SELECT  FID FROM T_BAS_ATTACHMENT WHERE FBILLTYPE = '{0}' AND FINTERID = '{1}' and FATTACHMENTNAME = '{2}'", "PUR_PurchaseOrder", InterId, FileName);
                                var dyExists = DBUtils.ExecuteDynamicObject(this.Context, sql);
                                var delAttchmentIds = new List<string>();
                                if (dyExists.Count > 0)
                                {
                                    foreach (var dye in dyExists)
                                    {
                                        delAttchmentIds.Add(dye["FID"].ToString());//构建需要删除的FID集合 
                                    }
                                }

                                if (delAttchmentIds.Count > 0)
                                {
                                    FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, "BOS_Attachment");

                                    DynamicObjectType wlType = meta.BusinessInfo.GetDynamicObjectType();

                                    BusinessDataServiceHelper.Delete(this.Context, delAttchmentIds.ToArray(), meta.BusinessInfo.GetDynamicObjectType());
                                }
                            }
                        }
                    }
                    else
                        return;
                }));
            }

            if (e.BarItemKey.EqualsIgnoreCase("tbCancelFile")) //作废合同文件
            {
                var FContractId = "";
                if (!this.View.Model.GetValue("FContractId").IsNullOrEmpty())
                    FContractId = this.View.Model.GetValue("FContractId").ToString().Trim();
                if (FContractId == "")
                {
                    this.View.ShowMessage("没有创建电子签约单");
                    return;
                }

                var FisCancelBill = Convert.ToBoolean(this.View.Model.GetValue("FisCancelBill").ToString());//是否已作废合同文件
                //if (FisCancelBill)
                //{
                //    this.View.ShowMessage("已发起作废，不允许重复发起");
                //    return;
                //}

                this.View.ShowMessage("确实要发起作废吗？", MessageBoxOptions.YesNo,
                new Action<MessageBoxResult>((MsgResult) =>
                {
                    if (MsgResult == MessageBoxResult.Yes)
                    {
                        var BillNo = this.View.Model.GetValue("FBillNo").ToString();
                        var PKID = Convert.ToInt32(this.View.Model.DataObject["Id"].ToString());
                        Common.GetParams(this.Context);
                        var sql = string.Format("exec SP_QYS_GetJsonPurOrderCancelBill {0},{1},'{2}'", PKID, FContractId, this.Context.UserName);
                        var dycollJson = DBUtils.ExecuteDynamicObject(this.Context, sql);
                        if (dycollJson.Count < 1)
                        {
                            this.View.ShowMessage("获取发起作废报文异常");
                            return;
                        }
                        var JsonData = JObject.Parse(dycollJson[0][0].ToString());
                        var ErrMsg = "";
                        var isPost = true;
                        var result = Common.PostBill(Common.CancelBillUrl, Common.AppToken, Common.AppSecret, JsonData, ref isPost);
                        if (!isPost)
                        {
                            ErrMsg = result.ToString().Trim();
                            string sqlerr = string.Format("update T_PUR_POORDER set FCCLMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                            DBUtils.Execute(this.Context, sqlerr);
                            this.View.ShowErrMessage("发起作废失败：" + ErrMsg);
                            return;
                        }
                        else
                        {
                            var JsonResult = result as JObject;
                            if (JsonResult["code"].ToString() != "0")
                            {
                                ErrMsg = "code【" + JsonResult["code"].ToString().Trim() + "】,message【" + JsonResult["message"].ToString().Trim() + "】";
                                string sqlerr = string.Format("update T_PUR_POORDER set FCCLMESSAGE = '" + ErrMsg.Replace("'", "''") + "' where FID = {0}", PKID);
                                DBUtils.Execute(this.Context, sqlerr);
                                this.View.ShowErrMessage("发起作废失败：" + ErrMsg);
                                return;
                            }
                            else
                            {
                                sql = string.Format("update T_PUR_POORDER set FISCANCELBILL = 1,FCCLMESSAGE = '作废成功' where FID = {0}", PKID);
                                DBUtils.Execute(this.Context, sql);
                                this.View.ShowMessage("作废成功！");

                                //撤回时删除已经上传的附件
                                var InterId = this.View.Model.DataObject["Id"].ToString();
                                var FileName = BillNo + ".PDF";//定义文件名：单据编号为文件名
                                sql = string.Format("SELECT  FID FROM T_BAS_ATTACHMENT WHERE FBILLTYPE = '{0}' AND FINTERID = '{1}' and FATTACHMENTNAME = '{2}'", "PUR_PurchaseOrder", InterId, FileName);
                                var dyExists = DBUtils.ExecuteDynamicObject(this.Context, sql);
                                var delAttchmentIds = new List<string>();
                                if (dyExists.Count > 0)
                                {
                                    foreach (var dye in dyExists)
                                    {
                                        delAttchmentIds.Add(dye["FID"].ToString());//构建需要删除的FID集合 
                                    }
                                }

                                if (delAttchmentIds.Count > 0)
                                {
                                    FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, "BOS_Attachment");

                                    DynamicObjectType wlType = meta.BusinessInfo.GetDynamicObjectType();

                                    BusinessDataServiceHelper.Delete(this.Context, delAttchmentIds.ToArray(), meta.BusinessInfo.GetDynamicObjectType());
                                }

                            }
                        }
                    }
                    else
                        return;
                }));
            }
        }
    }
}
